package cn.edu.tju.wallet.repository;

import cn.edu.tju.wallet.domain.RechargeRule;
import cn.edu.tju.wallet.domain.RechargeRule.RuleStatus;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 充值规则Repository接口
 */
@Repository
public interface RechargeRuleRepository extends JpaRepository<RechargeRule, Long> {

    /**
     * 查询所有激活的充值规则
     * @return 充值规则列表
     */
    List<RechargeRule> findByStatusOrderByPriorityDesc(RuleStatus status);

    /**
     * 查询适用于指定金额的充值规则（按优先级排序）
     * @param amount 充值金额
     * @param now 当前时间
     * @return 充值规则列表
     */
    @Query("SELECT r FROM RechargeRule r WHERE r.status = 'ACTIVE' " +
           "AND r.minAmount <= :amount " +
           "AND r.startTime <= :now " +
           "AND (r.endTime IS NULL OR r.endTime >= :now) " +
           "ORDER BY r.priority DESC, r.minAmount DESC")
    List<RechargeRule> findApplicableRules(@Param("amount") BigDecimal amount,@Param("now") LocalDateTime now);

    /**
     * 查询最佳充值规则（优先级最高且适用）
     * @param amount 充值金额
     * @param now 当前时间
     * @return 充值规则
     */
    @Query("SELECT r FROM RechargeRule r WHERE r.status = 'ACTIVE' " +
           "AND r.minAmount <= :amount " +
           "AND r.startTime <= :now " +
           "AND (r.endTime IS NULL OR r.endTime >= :now) " +
           "ORDER BY r.priority DESC, r.minAmount DESC")
    Optional<RechargeRule> findBestRule(@Param("amount") BigDecimal amount,@Param("now") LocalDateTime now);
}

